package DataStructures.Stack;


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author ：ALi
 * @date ：Created in 2021/11/4 19:21
 * @description：逆波兰计算器
 * @modified By：
 * @version: $
 */
public class PolandNotation {

    public static void main(String[] args){
        //逆波兰计算器：(3+4)*5-6 => 3 4 + 5 * 6 -
        String str = "3 4 + 5 * 6 -";
        List<String> rpnList = getListString(str);
        int res = Calculator(rpnList);
        System.out.println(res);
    }
    /**
     * create by: ALi
     * description: 分隔字符串
     * create time: 2021/11/4 20:10
     * @Param: null
     * @return  list型
     */
    public static List<String> getListString(String str){
        String[] split = str.split(" ");
        List<String> list = new ArrayList<String>();
        for (String item:split){
            list.add(item);
        }
        return list;

    }
    public static int Calculator(List<String> list){
        //创建一个栈
        Stack<String> stack = new Stack();
        int num1 = 0;
        int num2 = 0;
        int res = 0;
        for (String item : list)
            if (item.matches("\\d+")) {
                stack.push(item);
            } else {
                num2 = Integer.parseInt(stack.pop());
                num1 = Integer.parseInt(stack.pop());
                if ("-".equals(item)) {
                    res = num1 - num2;
                } else if ("+".equals(item)) {
                    res = num1 + num2;
                } else if ("*".equals(item)) {
                    res = num1 * num2;
                } else if ("/".equals(item)) {
                    res = num1 / num2;
                } else {
                    num1 = 0;
                    num2 = 0;
                    throw new RuntimeException("计算错误");
                }
                //将结果放入栈中
                stack.push(""+res);


            }
        return Integer.parseInt(stack.pop());
    }
}